﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using TuKu;
using TuKu.Load;
using System.Diagnostics;
using System.IO;

namespace TuKu
{
    public partial class ppsSubList : Form
    {
        DataTable dt=new DataTable();
        public ppsSubList()
        {
            InitializeComponent();
        }
        private void init()
        {

            foreach (DataRow dr in dt.Rows)
            {
                lstUrl.Items.Add(dr["categoryName"].ToString());
            }
            //txts.Text = System.Text.RegularExpressions.Regex.Replace(lstUrl.Items[0].ToString(), @"[^\d]*", "");
        }

        private void ppsSubList_Load(object sender, EventArgs e)
        {
            DataTable cate = new BLL.urlcate().GetList("  1=1 ").Tables[0];
            cmbppscategory.DataSource = cate;
            cmbppscategory.DisplayMember = "catename";
            cmbppscategory.ValueMember = "id";
            //cmbppscategory.SelectedValueChanged += new EventHandler(cmbppscategory_SelectedValueChanged);
        }

        void cmbppscategory_SelectedValueChanged(object sender, EventArgs e)
        {
            int catid = int.Parse(cmbppscategory.SelectedValue.ToString());
            this.Text = cmbppscategory.Text.ToString() + ":" + lstUrlDataBind(catid) + "条";
        }

        private int lstUrlDataBind(int catid)
        {
            DataTable dt = new BLL.urltable().GetList(" pagenumber>0 and categoryid=" + catid).Tables[0];
            lstUrl.DataSource = dt;
            lstUrl.DisplayMember = "url";
            lstUrl.ValueMember = "pagenumber";
            return lstUrl.Items.Count;
        }
        /// <summary>
        /// 清除分类字段标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImgSave_Click(object sender, EventArgs e)
        {

            StringBuilder strSql = new StringBuilder();
            string pattern = @"<div\s(.+)/"">|</a(.+)</div>";

            LoadingHandler.Show(this, LoadingStyle.Progress, args =>
            {
                args.MaxValue = dt.Rows.Count;

                foreach (DataRow dr in dt.Rows)
                {
                    args.Execute(ex =>
                  {
                      Maticsoft.DBUtility.DbHelperOleDb.ExecuteSql("update urltable set categoryName ='" + Regex.Replace(dr["categoryName"].ToString(), pattern, "") + "' where id=" + dr["id"].ToString());
                  });
                    args.Value++;
                    args.Change();
                    System.Threading.Thread.Sleep(5);
                }

            });

        }

        private void btnDataSource_Click(object sender, EventArgs e)
        {
            // DateTime sd = DateTime.Now;
            //lstUrl.DataSource = dt;
            //lstUrl.DisplayMember = "categoryName";
            //lstUrl.ValueMember = "categoryName";
            // DateTime ed = DateTime.Now;
            // TimeSpan span = ed - sd;
            //span.ToString().showBox();
        }
        /// <summary>
        /// 显示分类标签替换后结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstUrl_DoubleClick(object sender, EventArgs e)
        {
            string input = lstUrl.SelectedValue.ToString();
            string pattern = @"<div\s(.+)/"">|</a(.+)</div>";
            Regex.Replace(input, pattern, "").showBox();
        }

        private void lstUrl_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnGetSubUrl_Click(object sender, EventArgs e)
        {
            int catid = int.Parse(cmbppscategory.SelectedValue.ToString());
            Model.urlsubtable model = new global::TuKu.Model.urlsubtable();
            BLL.urlsubtable bll = new global::TuKu.BLL.urlsubtable();
            DataTable dt = new BLL.urltable().GetList(" pagenumber>0 and not finish and categoryid=" + catid.ToString()).Tables[0];
            LoadingHandler.Show(this, LoadingStyle.Progress, args =>
            {
                args.MaxValue = dt.Rows.Count;
                foreach (DataRow dr in dt.Rows)
                {
                    model.addtime = DateTime.Now;
                    model.categoryid = catid;
                    model.title = dr["title"].ToString();
                    model.picPage = "";
                    args.Execute(ex =>
                    {
                        for (int i = 2; i <= int.Parse(dr["pagenumber"].ToString()); i++)
                        {
                            model.currentpage = i;
                            model.url = dr["url"].ToString().Replace("index", i.ToString());
                            //if (!bll.Exist(model.url))
                            //{
                            bll.Add(model);
                            //}
                        }
                        args.Value++;
                        args.Change();
                        System.Threading.Thread.Sleep(1);
                    });

                }
            });
            string sql = "update urltable set finish=-1 where categoryid=" + catid.ToString();
            Maticsoft.DBUtility.DbHelperOleDb.ExecuteSql(sql);
            MessageBox.Show("完成");

        }

        private void getImgUrl_Click(object sender, EventArgs e)
        {
            ///style/img/nopicture.jpg
            DateTime st = DateTime.Now;
            int catid = int.Parse(cmbppscategory.SelectedValue.ToString());
            DataTable dt = new BLL.urlsubtable().GetList(" len(picpage)<10 and  categoryid=" + catid.ToString()).Tables[0];
            BLL.urlsubtable bll = new global::TuKu.BLL.urlsubtable();
            int i = 0;
            string imgurl = string.Empty;
            LoadingHandler.Show(this, LoadingStyle.Progress, args =>
         {
             args.MaxValue = dt.Rows.Count;
             foreach (DataRow dr in dt.Rows)
             {
                 if (i == textBox1.Text.toInt())
                 {
                     break;
                 }
                 args.Execute(ex =>
                    {
                        imgurl =new RegexClass().doRegex(dr["url"].ToString());
                        label1.Text = "id:" + dr["id"].ToString();
                        linkLabel1.Text = dr["url"].ToString();
                        textBox2.Text = imgurl;
                        bll.UpdateUrl(int.Parse(dr["id"].ToString()),imgurl);
                        if (checkBox1.Checked)
                        {
                            webBrowser1.DocumentText = "<img src=\"" + imgurl + "\"/>";
                        }
                        args.Value++;
                        args.Change();
                        System.Threading.Thread.Sleep(100);

                   });
                 i++;
             }

         });
            DateTime et = DateTime.Now;
            TimeSpan span = et - st;
            button1.Text = Maticsoft.DBUtility.DbHelperOleDb.GetSingle("select count(*) from urlsubtable where picpage<>''").ToString();
            
            //MessageBox.Show("处理"+dt.Rows.Count.ToString()+"条记录，用于"+span.ToString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text  = Maticsoft.DBUtility.DbHelperOleDb.GetSingle("select count(*) from urlsubtable where picpage<>''").ToString();
            string leftCount ="当前分类未处理数量:"+ Maticsoft.DBUtility.DbHelperOleDb.GetSingle("select count(*) from urlsubtable where picpage='' and categoryid=" + cmbppscategory.SelectedValue.ToString()).ToString();
            leftCount.showBox();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.ParentForm.WindowState = FormWindowState.Minimized;
            using (Process p = new Process())
            {
                if (File.Exists("C:\\Program Files\\Mozilla Firefox\\firefox.exe"))
                {
                    p.StartInfo.FileName = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
                }
                else
                {
                    p.StartInfo.FileName = "IEXPLORE.EXE";
                }
                p.StartInfo.Arguments = linkLabel1.Text;
                p.Start();
            }
        }




    }
}
